package com.ywd.materials.admin.config;

import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * MVC
 */
@AllArgsConstructor
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final AuthInterceptor authInterceptor;

    /**
     * 静态资源拦截
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 放开knife4j的html拦截
        registry.addResourceHandler("/api/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        // 放开knife4j的css和js拦截
        registry.addResourceHandler("/api/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        //放开knife4j的图片拦截
        registry.addResourceHandler("/api/img/**")
                .addResourceLocations("classpath:/META-INF/resources/img/");
        // 放开静态资源
        registry.addResourceHandler("/api/file/**")
                .addResourceLocations("classpath:META-INF/resources/static/file/");
    }

    /**
     * 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //放行路径
        List<String> excludePath = List.of(
                "/api/doc.html",
                "/api/swagger-ui.html",
                "/api/swagger-ui/**",
                "/api/swagger-resources/**",
                "/api/v3/api-docs/**",
                "/api/webjars/**",
                "/api/resources/**",
                "/api/static/**",
                "/api/error",
                "/api/favicon.ico");
        registry.addInterceptor(authInterceptor).excludePathPatterns(excludePath);
    }

    /**
     * 跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //允许跨域的路径
        registry.addMapping("/**")
                //请求头
                .allowedHeaders("*")
                //响应头
                .exposedHeaders("*")
                //证书
                .allowCredentials(true)
                //域名
                //.allowedOrigins()
                .allowedOriginPatterns("*")
                //方法
                .allowedMethods("*")
                //时间
                .maxAge(36000);
    }
}
